#ifndef __TASK_MANAGER_H__
#define __TASK_MANAGER_H__

#include <list>
#include <map>
#include	<stdint.h>
/*
#include <Ice/Ice.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/Thread.h>
*/
#include "Handle.h"
#include "Monitor.h"
#include "Thread.h"
#include "Exception.h"


#include "Singleton.h"

using namespace std;

namespace MyUtil {

class Task;
typedef IceUtil::Handle<Task> TaskPtr;
class TaskHandler;
typedef IceUtil::Handle<TaskHandler> TaskHandlerPtr;
class TaskManager;
typedef IceUtil::Handle<TaskManager> TaskManagerPtr;

//---------------------------------------------------------------------------
class Task : public IceUtil::Shared
{
public:
    Task(int level = 0);
    virtual ~Task() = 0;

    int level();
    void level(int level);

    virtual void handle() = 0;

protected:
    int _level;
};

//-----------------------------------------------------------------------
class TaskHandler :
    public IceUtil::Monitor<IceUtil::Mutex>,
    public IceUtil::Thread
{
public:
    TaskHandler();
    virtual ~TaskHandler();

    virtual void run();

    void stop();
    IceUtil::Time& activateTime();

    void handle(const TaskPtr& task);

private:
    IceUtil::Time _activateTime;
    bool _stopFlag;

    TaskPtr _task;
};


//---------------------------------------------------------------------------
class TaskManager : public IceUtil::Thread,
    public Singleton<TaskManager>
{
friend class TaskHandler;
public:
    virtual ~TaskManager();

    void initialize(uint32_t minHandlers,
                    uint32_t maxHandlers,
                    uint32_t handlerStackSize = 2097152,
                    uint32_t handlerIdleThreshold = 300);

    virtual void run();

    void push(const TaskPtr& task);
    TaskPtr pop();

private:
    TaskHandlerPtr getIdleHandler();
    TaskHandlerPtr createHandler();

    void handlerFinished(const TaskHandlerPtr& handler);
    void pinchHandlers();
    bool handlerIdleTimeout(const TaskHandlerPtr& handler);

    size_t taskSize();

private:
    typedef list<TaskPtr> TaskList;
    typedef map<int, TaskList> TaskMap;
    TaskMap          _tasks;

    typedef list<TaskHandlerPtr> TaskHandlerList;
    TaskHandlerList _busyHandlers;
    TaskHandlerList _idleHandlers;

    IceUtil::Monitor<IceUtil::Mutex> _handlerMutex;
    IceUtil::Monitor<IceUtil::Mutex> _taskMutex;

    uint32_t _minHandlers;
    uint32_t _maxHandlers;
    IceUtil::Time _handlerIdleThreshold;
    uint32_t _threadStackSize;
};


};
#endif


